﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SSCMS.Configuration;
using SSCMS.Services;
using SSCMS.Utils;
using WF.BeOnDuty.BeOnDuty;
using WF.BeOnDuty.Utils;

namespace WF.BeOnDuty.Controllers.Admin
{
    [Authorize(Roles = Types.Roles.Administrator)]
    [Route(Constants.ApiAdminPrefix + "/[controller]/")]
    public class DutyInfoController : ControllerBase
    {
        private readonly IAuthManager _authManager;
        private readonly IDutyInfoRepository _dutyInfoRepository;
        public DutyInfoController(IAuthManager authManager, IDutyInfoRepository dutyInfoRepository)
        {
            _authManager = authManager;
            _dutyInfoRepository = dutyInfoRepository;
        }
        [HttpGet("getPageList")]
        public async Task<ActionResult> GetPageList([FromQuery] int siteId, [FromQuery] int page, [FromQuery] int perPage = 15)
        {
            if (!await _authManager.HasSitePermissionsAsync(siteId, DutyInfoUtils.PermissionsDutyInfo))
            {
                return Unauthorized();
            }
            int total = await _dutyInfoRepository.GetCountAsync(siteId);
            var data = await _dutyInfoRepository.GetPageAsync(siteId, page, perPage);
            return Ok(new { code = 0, msg = "列表查询", total, data });
        }
        [HttpPost]
        public async Task<ActionResult> PostAdd([FromBody] Models.DutyInfo model)
        {
            var enity = await _dutyInfoRepository.GetDutyDateAsync(model.SiteId, model.DutyDate);
            if (model.Id == 0)
            {
                if (enity != null) 
                {
                    throw new Exception("该值班日期已经存在数据");
                }
                int id = await _dutyInfoRepository.InsertAsync(model);
                if (id == 0)
                {
                    return this.Error("添加失败!");
                }
                return Ok(new { code = 0, msg = "添加成功", data = model });

            }
            else
            {
                if (enity != null)
                {
                    if (enity.Id != model.Id)
                    {
                        throw new Exception("该值班日期已经存在数据");
                    }
                }
                bool result = await _dutyInfoRepository.UpdateAsync(model);
                if (result)
                {
                    return Ok(new { code = 0, msg = "修改成功", data = model });
                }
                else
                {
                    return this.Error("更新失败!");
                }
            }
        }


        [HttpPost("delete")]
        public async Task<ActionResult> Delete([FromQuery] int siteId, [FromQuery] int id)
        {
            bool result = await _dutyInfoRepository.DeleteAsync(siteId, id);
            if (result)
            {
                return Ok(new { code = 0, msg = "删除成功" });
            }
            else
            {
                return this.Error("删除失败!");
            }
        }

    }
}
